<template>
  <div class="container">
    <div v-if="loading" class="loading">正在加载数据，请稍候...</div>
    <div v-else-if="!hasData" class="no-data">暂无成绩数据可供展示。</div>

    <div v-else>
      <div class="fold-card" v-for="item in panels" :key="item.index">
        <div class="section-header" @click="toggle(item.index)">
          <p class="section-title">
            {{ item.title }}
            <i class="arrow" :class="{ rotate: active === item.index }"></i>
          </p>
        </div>
        <transition name="slide">
          <div class="chart" v-show="active === item.index" :id="item.chartId"></div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { useRoute } from 'vue-router'
import { ref, onMounted, nextTick } from 'vue'
import { getStuSemesterData } from '@/services/api'

export default {
  name: 'StuData',
  setup () {
    /* ···—————————— 1. 基础状态 ——————————··· */
    const route        = useRoute()
    const stu_id       = localStorage.getItem('id')
    const semester_id  = route.params.id
    const loading      = ref(true)
    const hasData      = ref(false)
    const active       = ref(1)

    const panels = [
      { index: 1, title: '考试成绩折线图', chartId: 'examChart' },
      { index: 2, title: '作业成绩柱状图', chartId: 'homeworkChart' },
      { index: 3, title: '总体成绩分布图', chartId: 'distributionChart' }
    ]

    /* ···—————————— 2. 数据缓存 ——————————··· */
    let examTitles = []
    let examScores = []
    let hmkTitles  = []
    let hmkScores  = []

    /* ···—————————— 3. 折叠切换 ——————————··· */
    const toggle = (idx) => {
      active.value = active.value === idx ? null : idx
      nextTick(() => {
        if (idx === 1) renderExamChart()
        if (idx === 2) renderHomeworkChart()
        if (idx === 3) renderPieChart()
      })
    }

    /* ···—————————— 4. 请求数据 ——————————··· */
    const fetchData = async () => {
      try {
        const { data } = await getStuSemesterData(stu_id, semester_id)
        loading.value = false
        if (data.status !== 1) return

        const exams = data.data.semStuExamDatas ?? []
        const hmks  = data.data.semStuHmkDatas ?? []

        examTitles = exams.map(e => e.paper_title)
        examScores = exams.map(e => e.get_score)
        hmkTitles  = hmks.map(h => h.hmk_title)
        hmkScores  = hmks.map(h => h.get_score)

        hasData.value = examTitles.length || hmkTitles.length
      } catch (e) {
        console.error(e)
        loading.value = false
      }
    }

    /* ========== 5‑1. 折线：考试成绩 ========= */
     const renderExamChart = () => {
      const chart = echarts.init(document.getElementById('examChart'))
      chart.setOption({
        backgroundColor: "1f1f1f",
        grid: { top: 60, left: 50, right: 30, bottom: 40 },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: examTitles,
          axisLine: { lineStyle: { color: '#4e6e8e' } },
          axisLabel: { color: '#9db3c6' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#9db3c6' },
          splitLine: { lineStyle: { color: '#23384d' } },
          axisLine: { show: false }
        },
        series: [
          {
            name: '成绩',
            type: 'line',
            smooth: true,
            data: examScores,
            symbol: 'circle',
            symbolSize: 9,
            lineStyle: { width: 3, color: '#05d2ff' },
            itemStyle: {
              color: '#05d2ff',
              shadowBlur: 10,
              shadowColor: '#05d2ff'
            },
            areaStyle: {
              opacity: 0.25,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(5,210,255,0.45)' },
                { offset: 1, color: 'rgba(5,210,255,0)' }
              ])
            },
            animationDuration: 1200,
            animationEasing: 'cubicOut'
          },
          {
            // 节点波纹
            type: 'effectScatter',
            coordinateSystem: 'cartesian2d',
            data: examScores.map((v, i) => [examTitles[i], v]),
            symbolSize: 12,
            rippleEffect: { brushType: 'stroke', scale: 3 },
            itemStyle: { color: '#37f5ff' },
            tooltip: { show: false }
          }
        ]
      })
      window.addEventListener('resize', chart.resize)
    }

    /* ========== 5‑2. 柱状：作业成绩 ========= */
    const renderHomeworkChart = () => {
      const chart = echarts.init(document.getElementById('homeworkChart'))
      chart.setOption({
        backgroundColor: "1f1f1f",
        grid: { top: 60, left: 50, right: 30, bottom: 40 },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: hmkTitles,
          axisLine: { lineStyle: { color: '#4e6e8e' } },
          axisLabel: { color: '#9db3c6', rotate: 30 }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#9db3c6' },
          splitLine: { lineStyle: { color: '#23384d' } },
          axisLine: { show: false }
        },
        series: [{
          type: 'bar',
          barWidth: 18,
          data: hmkScores,
          itemStyle: {
            borderRadius: [6, 6, 0, 0],
            color: params => {
              const hue = (params.dataIndex * 45) % 360
              return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: `hsl(${hue}, 90%, 60%)` },
                { offset: 1, color: `hsl(${hue}, 90%, 40%)` }
              ])
            },
            shadowBlur: 7, shadowColor: 'rgba(0,0,0,0.4)'
          },
          emphasis: { scale: true },
          animationEasing: 'elasticOut',
          animationDelay: p => p.dataIndex * 50
        }]
      })
      window.addEventListener('resize', chart.resize)
    }

    /* ========== 5‑3. 饼图：成绩分布 ========= */
    const renderPieChart = () => {
      const all  = [...examScores, ...hmkScores]
      const pass = all.filter(x => x >= 60).length
      const fail = all.length - pass

      const chart = echarts.init(document.getElementById('distributionChart'))
      chart.setOption({
        backgroundColor: "1f1f1f",
        legend: { top: 10, left: 'center', textStyle: { color: '#ccc' } },
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: ['45%', '65%'],
          label: { color: '#eee', fontSize: 14 },
          data: [
            { value: pass, name: '及格',  itemStyle: { color: '#00e676' } },
            { value: fail, name: '不及格', itemStyle: { color: '#ff5252' } }
          ],
          // 简单发光效果
          emphasis: {
            scale: true,
            scaleSize: 8,
            itemStyle: { shadowBlur: 25, shadowColor: 'rgba(255,255,255,0.6)' }
          },
          animationDuration: 800,
          animationEasing: 'cubicOut'
        }]
      })
      window.addEventListener('resize', chart.resize)
    }

    /* ···—————————— 6. 生命周期 ——————————··· */
    onMounted(async () => {
      await fetchData()
      renderExamChart()   // 默认展开第一张
    })

    return { loading, hasData, active, toggle, panels }
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
  min-height: 100vh;
  background-image: linear-gradient(to top, #09203f 0%, #537895 100%);
  border-radius: 10px;
  color: #f0f0f0;
  box-sizing: border-box;
}

.fold-card {
  margin-bottom: 16px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.04);
  backdrop-filter: blur(8px);
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
  transition: all 0.3s ease;
}

.section-header {
  cursor: pointer;
  padding: 16px 24px;
  background: rgba(255, 255, 255, 0.05);
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #ffffff;
  font-size: 16px;
  user-select: none;
}

.section-header:hover {
  background: rgba(255, 255, 255, 0.08);
}

.section-title {
  margin: 0;
  flex: 1;
}

.arrow {
  border: solid #aaa;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 5px;
  transform: rotate(45deg);
  transition: transform 0.3s ease;
}

.arrow.rotate {
  transform: rotate(-135deg);
}

.chart {
  width: 100%;
  height: 400px;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.loading,
.no-data {
  text-align: center;
  font-size: 18px;
  color: #bbb;
  margin-top: 100px;
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
  max-height: 1000px;
  overflow: hidden;
}

.slide-enter,
.slide-leave-to {
  max-height: 0;
  opacity: 0;
}
.container {
  font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', sans-serif;
}
</style>
